<template>
  <div class="edit-wrapper">
    <div class="search-wrapper">
      <n-space>
        <!-- <n-select
        style="width: 80px"
        size="small"
        v-model:value="selectSearchType"
        :options="searchTypeOptions"
      ></n-select> -->
        <n-popover v-if="selectSearchType == 0" trigger="click">
          <template #trigger>
            <n-input
              placeholder="请输入地点名称"
              style="width: 200px"
              size="small"
              v-model:value="searchText"
            ></n-input>
          </template>
          <div class="search-content">
            <n-scrollbar style="height: 300px">
              <n-tree
                block-line
                selectable
                :data="searchData"
                :on-load="handleLoad"
                :check-strategy="'all'"
                :allow-checking-not-loaded="true"
                :cascade="true"
                expand-on-click
                :scrollbar-props="{ size: 300 }"
                @update:selected-keys="handleSelect"
              />
            </n-scrollbar>
          </div>
        </n-popover>

        <n-input
          v-if="selectSearchType == 1"
          pair
          separator="-"
          :placeholder="['经度', '纬度']"
          clearable
          size="small"
          v-model:value="searchCoordiante"
        />
      </n-space>
    </div>
    <div class="edit-panel">
      <template v-for="(item, index) in buttonList">
        <n-tooltip
          v-if="
            item.type == 'button' &&
            (!item.visible || item.visible == mapStore.drawMode)
          "
          placement="bottom"
          trigger="hover"
        >
          <template #trigger>
            <div
              @click="handleButtonTap(index)"
              :class="[
                'edit-button',
                index == selectButtonIndex ? 'active' : '',
              ]"
            >
              <n-icon size="16">
                <component :is="item.icon()"></component>
              </n-icon>
            </div>
          </template>
          <span>{{ item.name }} </span>
        </n-tooltip>
        <n-divider v-if="item.type == 'divider'" vertical></n-divider>
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import {
  PinOutline,
  TrashOutline,
  MoveOutline,
  EllipseOutline,
  ScanOutline,
  ArrowDownCircleOutline,
  TextOutline,
  ArrowForwardOutline,
} from "@vicons/ionicons5";
import { TreeOption, useMessage, useModal } from "naive-ui";
import WKT from "terraformer-wkt-parser";
// import BrushFreehand from "@/assets/svg/BrushFreehand.svg";
import svgIcon from "@/components/svg/index.vue";
import { useEventBus } from "@vueuse/core";
import { h } from "vue";
import { useMapStore } from "@/store/map";
import { addFeature } from "@/api";
import * as dayjs from "dayjs";
import * as turf from "@turf/turf";
import { watchThrottled } from "@vueuse/core";
import polttingPanel from "./plotting.vue";
const mapBus = useEventBus("map");
const mapStore = useMapStore();
const selectButtonIndex = ref(0);
const message = useMessage();
const layerConfigBus = useEventBus("layer.config");
const searchText = ref("");
const searchCoordiante = ref([]);
const selectProvinceCode = ref("");
const selectCityCode = ref("");
const modal = useModal();
// const plottingModal = useModal();
const searchData = ref([]);
const searchTypeOptions = [
  {
    label: "地名",
    value: 0,
  },
  {
    label: "坐标",
    value: 1,
  },
];

const selectSearchType = ref(0);
// console.log(BrushFreehand);
const renderGeojson = (data: any) => {
  const layer = mapStore.getCurrentLayer();
  layer.features.push(data);

  mapBus.emit({
    type: "render.layer",
    value: layer,
  });
};
const buttonList = ref([
  {
    name: "移动模式",
    type: "button",
    icon: () => MoveOutline,
    tap: () => {},
  },
  {
    type: "divider",
    icon: () => {},
    tap: () => {},
  },
  {
    name: "绘制图标",
    type: "button",
    icon: () => PinOutline,
    visible: "Symbol",
    tap: () => {
      console.log("draw.point");
      mapBus.emit({
        type: "draw.point",
        callback: (e) => {
          const data = {
            name: "新建点位",
            geometry: e[0].geometry,
            center: e[0].geometry,
            parent: mapStore.selectLayer,
            pid: e[0].id,
            img: "",
            properties: {
              pid: e[0].id,
            },
          };
          addFeature({
            ...data,
            geometry: WKT.convert(data.geometry),
            center: WKT.convert(data.center),
          })
            .then((res) => {
              message.success("添加成功");
              mapBus.emit({ type: "edit.clear" });
              selectButtonIndex.value = 0;
              renderGeojson(data);
              // const features = mapStore.getCurrentFeatures();

              // mapBus.emit({ type: "render", value: features });
              // layerConfigBus.emit({ type: "update" });
            })
            .catch((e) => {
              message.error(`添加失败:${e}`);
            });

          // console.log(features);
        },
      });
    },
  },
  {
    name: "绘制点",
    type: "button",
    icon: () => PinOutline,
    visible: "Point",
    tap: () => {
      console.log("draw.point");
      mapBus.emit({
        type: "draw.point",
        callback: (e) => {
          const data = {
            name: "新建点位",
            geometry: e[0].geometry,
            center: e[0].geometry,
            parent: mapStore.selectLayer,
            pid: e[0].id,
            img: "",
            properties: {
              pid: e[0].id,
            },
          };
          addFeature({
            ...data,
            geometry: WKT.convert(data.geometry),
            center: WKT.convert(data.center),
          })
            .then((res: any) => {
              data["id"] = res.data.id;
              data["updateTime"] = res.data.updateTime;
              message.success("添加成功");
              mapBus.emit({ type: "edit.clear" });
              selectButtonIndex.value = 0;
              renderGeojson(data);
              // const features = mapStore.getCurrentFeatures();

              // mapBus.emit({ type: "render", value: features });
              // layerConfigBus.emit({ type: "update" });
            })
            .catch((e) => {
              message.error(`添加失败:${e}`);
            });

          // console.log(features);
        },
      });
    },
  },
  {
    name: "涂鸦",
    type: "button",
    icon: () => h(svgIcon, { name: "BrushFreehand" }),
    tap: () => {},
    visible: "Polygon",
  },
  {
    name: "绘制多边形",
    type: "button",
    icon: () => h(svgIcon, { name: "Polygon" }),
    tap: () => {
      console.log("draw.polygon");
      mapBus.emit({
        type: "draw.polygon",
        callback: (e) => {
          console.log(e);
          const center = turf.centroid(e[0].geometry);
          console.log(center);
          const data = {
            name: "新建面",
            geometry: e[0].geometry,
            center: center.geometry,
            parent: mapStore.selectLayer,
            pid: e[0].id,
            img: "",
            properties: {
              pid: e[0].id,
            },
          };
          addFeature({
            ...data,
            geometry: WKT.convert(data.geometry),
            center: WKT.convert(data.center),
          })
            .then((res) => {
              message.success("添加成功");
              mapBus.emit({ type: "edit.clear" });
              selectButtonIndex.value = 0;
              renderGeojson(data);
              // layerConfigBus.emit({ type: "update" });
            })
            .catch((e) => {
              message.error(`添加失败:${e}`);
            });

          // console.log(features);
        },
      });
    },
    visible: "Polygon",
  },
  {
    name: "绘制钳击箭头",
    type: "button",
    icon: () => h(svgIcon, { name: "KeyboardDoubleArrowRightRound" }),
    tap: () => {
      console.log("draw.polygon");
      mapBus.emit({
        type: "draw.doubleArrow",
        callback: (e) => {
          // console.log(e);
          // const center = turf.centroid(e[0].geometry);
          // console.log(center);
          // const data = {
          //   name: "新建面",
          //   geometry: e[0].geometry,
          //   center: center.geometry,
          //   parent: mapStore.selectLayer,
          //   pid: e[0].id,
          //   img: "",
          //   properties: {
          //     pid: e[0].id,
          //   },
          // };
          // addFeature({
          //   ...data,
          //   geometry: WKT.convert(data.geometry),
          //   center: WKT.convert(data.center),
          // })
          //   .then((res) => {
          //     message.success("添加成功");
          //     mapBus.emit({ type: "edit.clear" });
          //     selectButtonIndex.value = 0;
          //     renderGeojson(data);
          //     // layerConfigBus.emit({ type: "update" });
          //   })
          //   .catch((e) => {
          //     message.error(`添加失败:${e}`);
          //   });
          // console.log(features);
        },
      });
    },
    visible: "plotting",
  },
  {
    name: "绘制燕尾箭头",
    type: "button",
    icon: () => h(svgIcon, { name: "ArrowTopTail" }),
    tap: () => {
      console.log("draw.polygon");
      mapBus.emit({
        type: "draw.tailsquadarrow",
        callback: (e) => {},
      });
    },
    visible: "plotting",
  },
  {
    name: "绘制细箭头",
    type: "button",
    icon: () => ArrowForwardOutline,
    tap: () => {
      console.log("draw.straightarrow");
      mapBus.emit({
        type: "draw.straightarrow",
        callback: (e) => {},
      });
    },
    visible: "plotting",
  },
  {
    name: "绘制文字",
    type: "button",
    icon: () => TextOutline,
    tap: () => {
      console.log("draw.polygon");
      mapBus.emit({
        type: "draw.text",
        callback: (e) => {},
      });
    },
    visible: "plotting",
  },
  {
    name: "绘制标绘图",
    type: "button",
    icon: () => ArrowDownCircleOutline,
    visible: "plotting",
    tap: () => {
      const plottingModal = modal.create({
        title: "选择标绘",
        content: () =>
          h(
            polttingPanel,
            {
              onSelect(name: string) {
                plottingModal.destroy();
              },
            },
            { default: () => {} }
          ),
        preset: "confirm",
        class: "plotting",
      });
    },
  },
  {
    name: "绘制线段",
    type: "button",
    icon: () => h(svgIcon, { name: "PolylineOutlined" }),
    tap: () => {
      mapBus.emit({
        type: "draw.lineString",
        callback: (e) => {
          console.log(e);
          const center = turf.centroid(e[0].geometry);
          console.log(center);
          const data = {
            name: "新建线段",
            geometry: e[0].geometry,
            center: center.geometry,
            parent: mapStore.selectLayer,
            pid: e[0].id,
            img: "",
            properties: {
              pid: e[0].id,
            },
          };
          addFeature({
            ...data,
            geometry: WKT.convert(data.geometry),
            center: WKT.convert(data.center),
          })
            .then((res) => {
              message.success("添加成功");
              mapBus.emit({ type: "edit.clear" });
              selectButtonIndex.value = 0;
              renderGeojson(data);
              // layerConfigBus.emit({ type: "update" });
            })
            .catch((e) => {
              message.error(`添加失败:${e}`);
            });

          // console.log(features);
        },
      });
    },
    visible: "LineString",
  },
  {
    type: "divider",
    icon: () => {},
    tap: () => {},
  },
  {
    name: "圈选",
    type: "button",
    icon: () => EllipseOutline,
    tap: () => {},
  },
  {
    name: "框选",
    type: "button",
    icon: () => ScanOutline,
    tap: () => {
      mapBus.emit({
        type: "draw.scaleRotate",
      });
    },
  },
  {
    name: "删除",
    type: "button",
    icon: () => TrashOutline,
    tap: () => {
      mapStore.selectPlottingName = "";
    },
  },
]);
const handleButtonTap = (index: number) => {
  selectButtonIndex.value = index;
  if (buttonList.value[index].tap) {
    buttonList.value[index].tap();
  }
};
const handleSearch = () => {
  const bounds = [-180, -90, 180, 90];
  fetch(
    `http://api.tianditu.gov.cn/v2/search?postStr={"keyWord":"${
      searchText.value
    }","level":1,"mapBound":"${bounds?.join(
      ","
    )}","queryType":1,"start":0,"count":10,show:1,"specify":"156000000"}&type=query&tk=350e148c7a6b26647f202dc9a5de1cef`
  ).then((res) => {
    res.json().then((data: any) => {
      console.log(data);
      if (data.statistics) {
        searchData.value = data.statistics.allAdmins.map((item) => {
          return {
            label: item.adminName,
            isLeaf: false,
            key: item.adminCode,
          };
        });
      } else if (data.pois) {
        searchData.value = data.pois.map((item) => {
          return {
            label: item.name,
            isLeaf: true,
            key: item.lonlat,
          };
        });
      }

      // searchList.value = data.pois || [];
      // setTimeout(() => {
      //   showToolTip.value = true;
      // });
    });
  });
};
const handleLoad = (node: TreeOption) => {
  return new Promise<void>((resolve) => {
    const bounds = [-180, -90, 180, 90];
    fetch(
      `http://api.tianditu.gov.cn/v2/search?postStr={"keyWord":"${
        searchText.value
      }","level":1,"mapBound":"${bounds?.join(
        ","
      )}","queryType":1,"start":0,"count":10,show:1,"specify":"${
        node.key
      }"}&type=query&tk=350e148c7a6b26647f202dc9a5de1cef`
    ).then((res) => {
      res.json().then((data: any) => {
        console.log(data);
        if (data.statistics) {
          node.children = data.statistics.allAdmins.map((item) => {
            return {
              label: item.adminName,
              isLeaf: false,
              key: item.adminCode,
            };
          });
          resolve();
        } else if (data.pois) {
          node.children = data.pois.map((item) => {
            return {
              label: item.name,
              isLeaf: true,
              key: item.lonlat,
            };
          });
          resolve();
        }

        // searchList.value = data.pois || [];
        // setTimeout(() => {
        //   showToolTip.value = true;
        // });
      });
    });
    // setTimeout(() => {
    //   node.children = [
    //     {
    //       label: "123123",
    //       key: Math.random() + "123132",
    //       isLeaf: false,
    //     },
    //   ];
    //   resolve();
    // }, 1000);
  });
};
watchThrottled(
  () => searchText.value,
  () => {
    handleSearch();
  },
  { throttle: 500 }
);
const handleSelect = (keys: Array<string>) => {
  console.log(keys);
  if (keys.length > 0) {
    const key = keys[0];
    if (typeof key == "string") {
      const center = keys[0].split(",");
      console.log(center);
      mapBus.emit({ type: "marker", center });
    }
  }
};
</script>

<style lang="scss" scoped>
.edit-wrapper {
  position: absolute;
  left: 12px;
  top: 12px;

  display: flex;
  align-items: center;
  justify-content: space-between;
  width: calc(100% - 24px);
}
.edit-panel {
  border-radius: 4px;
  backdrop-filter: blur(4px);
  box-sizing: border-box;
  padding: 3px;
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.1);
  flex: 1;
  .edit-button {
    width: 18px;
    height: 18px;
    padding: 6px;
    cursor: pointer;
    border-radius: 4px;
    margin-right: 3px;
  }
  .active {
    background-color: rgba(255, 255, 255, 0.2);
  }
  .edit-button:hover {
    background-color: rgba(255, 255, 255, 0.1);
  }
  .edit-button:active {
    background-color: rgba(255, 255, 255, 0.2);
  }
}
.search-wrapper {
  margin-right: 12px;
  height: 36px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  backdrop-filter: blur(4px);
  box-sizing: border-box;
  padding: 3px;
  display: flex;
  align-items: center;
}
.search-content {
  width: 500px;
  height: 300px;

  .search-title {
    font-weight: bold;
  }
}
</style>

<style lang="scss">
.plotting {
  width: 800px !important;
}
</style>
